const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const fs = require('fs')
const verifyToken = require('../../middleware/verifyToken')


router
// 登录
.post('/login', async (ctx, next) => {
  const query = ctx.request.body
  const user = await ctx.db.AdminUsers.findOne({username: query.username})
  let tokenKey
  try {
    tokenKey = fs.readFileSync('./assets/key/tokenKey.key', 'utf-8') 
  } catch (error) { 
    console.log(error)
  }
  if(user) {
    
    // 验证密码
    const isPasswordValid = require('bcrypt').compareSync(
      query.password,
      user.password
    )
    if(isPasswordValid) {
      // 验证token
      const token = jwt.sign({
        id: String(user._id),
        username: String(user.username) 
      }, tokenKey)
      ctx.body =  {
        code: 0,
        message: '登录成功',
        data: {
          token: token,
          username: user.username,
          id: user._id,
        }
      }
    }else {
      ctx.body =  { code: 1, message: '用户密码错误' }
    }
  }else {
    ctx.body =  { code: 1, message: '用户未注册' }
  }
})
// 注册
.post('/register', async (ctx, next) => {
  const query = ctx.request.body
  let registerKey
  try {
    registerKey = fs.readFileSync('./assets/key/register.key', 'utf-8')
  } catch (error) {
    console.log(error)
  }
  if(query.registerKey !== registerKey) { // 判断注册密钥是否正确
    ctx.body =  {
      code: 1,
      message: '注册密钥不正确'
    }
  }
  else {
    console.log('1')
    if(await ctx.db.AdminUsers.findOne({username: query.registerUsername})){
      ctx.body = {
        code: 1,
        message: '用户已存在'
      }
    }else {
      await ctx.db.AdminUsers.create({
        username: query.registerUsername,
        password: query.registerPassword,
        date: String(new Date) 
      })
      ctx.body =  {
        code: 0,
        message: '用户注册成功'
      }
    }
  }
})

// 上传文件
.use(require('./upload').routes(), require('./upload').allowedMethods())

// 验证Toeken
.use(verifyToken())

// 公共管理接口
.use(require('./common').routes(), require('./common').allowedMethods())

// 用户信息接口
.use(require('./user').routes(), require('./user').allowedMethods())

// 文章管理接口
.use('/article', require('./article').routes(), require('./article').allowedMethods())

// 留言管理接口
.use(require('./guest').routes(), require('./guest').allowedMethods())

// 轮播图管理接口
.use(require('./slidesShow').routes(), require('./slidesShow').allowedMethods())

module.exports = router